import numpy as np
import tkinter as tk
from PIL import Image, ImageTk


def center(master, *args):
    width, height = get_data_from_iter(args)
    x = (master.winfo_screenwidth() - width) // 2
    y = (master.winfo_screenheight() - height) // 2
    master.geometry(f"{width}x{height}+{x}+{y}")


def get_root(component):
    while True:
        if isinstance(component, tk.Tk):
            return component
        component = component.master


def draw(canvas: tk.Canvas, column, row, color, **kwargs):
    if row < 0 or column < 0:
        return
    offset = kwargs.get('offset', (0, 0))
    size = kwargs.get('size', 30)
    broder = kwargs.get('broder', 'grey')
    width = kwargs.get('width', 2)
    start_x = column * size + offset[0]
    start_y = row * size + offset[1]
    canvas.create_rectangle(start_x, start_y, start_x + size, start_y + size, fill=color,
                            outline=broder, width=width)


def get_data_from_iter(sources):
    result = []
    for data in sources:
        if isinstance(data, (tuple, list)):
            result += get_data_from_iter(data)
        else:
            result.append(data)
    return result


def modify_array_by_column(arr, value):
    # 创建一个布尔数组，表示每列是否所有元素都不等于指定的值
    all_not_equal = np.all(arr != value, axis=0)
    # 使用布尔索引保留不是所有元素都不等于指定值的列（即至少有一个元素等于value的列）
    filtered_cols = arr[:, ~all_not_equal]
    # 计算被删除的列数
    num_deleted_cols = np.sum(all_not_equal)
    # 整合两个array对象
    modified_arr = np.column_stack((np.full((arr.shape[0], num_deleted_cols), value), filtered_cols)) \
        if num_deleted_cols != 0 else filtered_cols
    return modified_arr, num_deleted_cols


def create_root(*args, **kwargs):
    new_root = tk.Tk()
    title = kwargs.get('title', 'tk')
    icon_path = kwargs.get('icon', None)
    if icon_path is not None:
        image = Image.open(icon_path)
        photo = ImageTk.PhotoImage(image)
        new_root.iconphoto(False, photo)
    center(new_root, args)
    new_root.title(title)
    return new_root





